package com.example.demo.service.thread.lock;

/**
 * @Description: 不可重入锁
 * @Author: kangyang
 * @DateTime: 2024/10/16 15:29
 **/
public class NonReentrantLock {
    private boolean isLocked = false;
    private Thread lockedBy = null;

    public void lock() throws InterruptedException {
        if (Thread.currentThread() == lockedBy) {
            throw new IllegalStateException("Cannot re-enter lock");
        }
        synchronized (this) {
            while (isLocked) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            isLocked = true;
            lockedBy = Thread.currentThread();
        }
    }

    public synchronized void unlock() {
        if (Thread.currentThread() == lockedBy) {
            isLocked = false;
            lockedBy = null;
            notify();
        }
    }
}
